package com.gongpingjialoan.activity.car;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.adapter.CarSourceListAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.bean.VipBuycarBean;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.network.NetDataJson.OnNetDataJsonListener;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.widget.LoadingDialog;
import com.handmark.pulltorefresh.library.PullToRefreshBase;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统推荐车
 * Created by chuang on 2016/8/8.
 */
public class SysRecomendCarActivity extends BaseActivity implements AdapterView.OnItemClickListener, OnNetDataJsonListener, PullToRefreshBase.OnRefreshListener<ListView>, PullToRefreshBase.OnLastItemVisibleListener {

    private NetDataJson mNetDataJson;

    private ListView listView;

    private CarSourceListAdapter mSysRecommendAdapter;

    private List<CarSource> carSourceDataList = new ArrayList<>();

    private VipBuycarBean mVipBuycarBean;

    private LoadingDialog loadingDialog;

    private ImageView nodataImageView;

    private View footView;

    private TextView moreTextView;

    private boolean isAddFootView = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        action = "system_recommend_car";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sys_recomend_car_layout);
        setTitle("VIP系统推荐车");
        initView();
        refreshData();
    }

    private void initView() {
        mVipBuycarBean = new VipBuycarBean();
        loadingDialog = new LoadingDialog(this);
        mSysRecommendAdapter = new CarSourceListAdapter(this);
        nodataImageView = (ImageView) findViewById(R.id.no_info);
        listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(mSysRecommendAdapter);
        listView.setOnItemClickListener(this);
        footView = LayoutInflater.from(this).inflate(R.layout.vip_car_footview, null);
        moreTextView = (TextView) footView.findViewById(R.id.more_car);
        moreTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SysRecomendCarActivity.this, CarListActivity.class);
                intent.putExtra("type", "vip_no_domain");
                intent.putExtra("mVipBuycarBean", mVipBuycarBean);
                startActivity(intent);
            }
        });
    }


    private void refreshData() {
        nodataImageView.setVisibility(View.GONE);
        getData();
    }

    private void getData() {
        if (mNetDataJson == null) {
            mNetDataJson = new NetDataJson(this);
        }
        mNetDataJson.clearMap();
        mNetDataJson.setUrl(API.Sys_recomend_car);
        mNetDataJson.addParam("device_code", GPJApplication.getInstance().getDeviceCode());
        mNetDataJson.request("get");
        loadingDialog.show();
    }


    @Override
    public void onDataJsonError(String errorMessage) {
        loadingDialog.dismiss();
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        JSONArray jsonArray = null;
        listView.setVisibility(View.VISIBLE);
        loadingDialog.dismiss();
        try {
//            JSONObject jb = json.getJSONObject("cars");
            jsonArray = json.getJSONArray("car_list");
            if (0 == jsonArray.length()) {
                nodataImageView.setVisibility(View.VISIBLE);
                return;
            }
            getDataFromJsonArray(jsonArray);
//            changeColor(json);
//            JSONObject jb2 = json.getJSONObject("filter");
//            getSysBuycarBean(jb2);
        } catch (Exception e) {
            if (jsonArray == null || 0 == jsonArray.length()) {
                nodataImageView.setVisibility(View.VISIBLE);
                return;
            }
        }
        updateListView();
    }


    public void updateListView() {
        if (carSourceDataList.size() != 0) {
            mSysRecommendAdapter.setData(carSourceDataList);
        }
    }

    @Override
    public void onLastItemVisible() {
    }


    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refreshData();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        intent.setClass(this, CarBuyDetailActivity.class);
        CarSource carSource = (CarSource) view.getTag(R.id.tag_second);
        intent.putExtra("typevalue", String.valueOf(carSource.mId));
        intent.putExtra("type", "sys_no_domain");
        startActivity(intent);
    }


    private void getDataFromJsonArray(JSONArray jsonArray) throws JSONException {
        for (int i = 0; i < jsonArray.length(); i++) {
            CarSource carSrc = new CarSource();
            JSONObject object = jsonArray.getJSONObject(i);
//            carSrc.car_num = object.getInt("car_num");
            carSrc.mTitle = object.getString("title");
            carSrc.mYear = object.getString("year");
            carSrc.mMile = object.getString("mile").equals("None") ? "" : object.getString("mile");
            carSrc.mPrice = Double.valueOf(object.getString("price"));
            carSrc.mId = object.getInt("id");
            carSrc.mThumbnail = object.getString("thumbnail");
            carSrc.mTime = object.getString("time");
            carSrc.hasmodel = object.getString("has_model_detail");
            carSrc.is_certify = object.getBoolean("is_certify");
            carSrc.pub_timestamp = object.getString("pub_timestamp");
            carSrc.mSourceType = object.getString("source_type");
            carSrc.mGpjIndex = object.getDouble("gpj_index");
            carSrc.mQsTags = object.getString("qs_tags");
            carSrc.mSource = object.getString("domain");
            carSrc.dealer_category = object.getString("dealer_category");
            carSrc.pubTime = object.getString("pub_time");
            carSrc.brand_zh = object.getString("brand_slug_zh");
            carSrc.model_zh = object.getString("model_slug_zh");
            carSrc.model_detail_zh = object.getString("model_detail_slug_zh");
            carSrc.setBrand(object.getString("brand_slug"));
            carSrc.setModel(object.getString("model_slug"));
            carSrc.mUrl = carSrc.mThumbnail;
            carSourceDataList.add(carSrc);
        }
    }


    private String getDataJsonArray(JSONArray jsonArray) throws Exception {
        StringBuilder sb = new StringBuilder();
        if (jsonArray == null || jsonArray.length() == 0)
            return "";
        int size = jsonArray.length();
        for (int j = 0; j < size; j++) {
            String brand_model_zh = jsonArray.get(j).toString();
            sb.append(brand_model_zh);
            if (j < size - 1) {
                sb.append(",");
            }
        }
        return sb.toString();
    }

    private String getAgeandMile(String start, String end) {
        if (TextUtils.isEmpty(start) && TextUtils.isEmpty(end))
            return "";
        if (!TextUtils.isEmpty(start) && TextUtils.isEmpty(end)) {
            return start + "-";
        }
        return start + "-" + end;
    }

    private void getSysBuycarBean(JSONObject object) throws Exception {
//        mVipBuycarBean.setId(object.getString("id"));
//        mVipBuycarBean.setTimes(object.getString("expect_period"));
//        mVipBuycarBean.setPrice(object.getString("price"));
//        mVipBuycarBean.setType(object.getString("vip_buy_type"));
//        mVipBuycarBean.setCity(object.getString("city"));
//
//        if ("ambiguous".equals(mVipBuycarBean.getType())) {
//            mVipBuycarBean.setItent(getDataJsonArray(object.getJSONArray("vehicle_model")));
//            mVipBuycarBean.setFunction(getDataJsonArray(object.getJSONArray("uses")));
//            mVipBuycarBean.setOthers(getDataJsonArray(object.getJSONArray("other_recommend")));
//        } else {
//            mVipBuycarBean.setAge(object.getString("age_h"));
//            mVipBuycarBean.setBrand_models(object.getString("brand_models"));
//            mVipBuycarBean.setMile(getAgeandMile(object.getString("mile_l"), object.getString("mile_h")));
//            mVipBuycarBean.setColors(getDataJsonArray(object.getJSONArray("colors")));
//        }
//        mSysRecommendAdapter.setData(mVipBuycarBean);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
    }

    private void changeColor(JSONObject json) throws Exception {
        if (!isAddFootView) {
            listView.addFooterView(footView);
            isAddFootView = true;
        }
        int allnumber = json.getInt("car_num");
        String number;
        if (allnumber > 1000) {
            number = "1000+";
        } else {
            number = allnumber + "";
        }
        String str = "还有" + number + "辆车源符合您的条件,点击查看更多";
        moreTextView.setText(Utils.changeColor(this, str, 2, 2 + number.length(), R.color.like_car_color));
    }
}
